package top.saplf.sileny.net.gank

import io.reactivex.Observable
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.http.GET
import retrofit2.http.Path

/**
 * @author saplf
 */
data class Result(
        val error: Boolean,
        val results: List<GankItem>
)

data class GankItem(
        val _id: String,
        val createdAt: String,
        val desc: String,
        val images: List<String>?,
        val publishedAt: String,
        val source: String,
        val type: String,
        val url: String,
        val used: Boolean,
        val who: String?
)

private val gankRetrofit: Retrofit by lazy {
    Retrofit.Builder()
            .baseUrl("http://gank.io/api/")
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .addConverterFactory(GsonConverterFactory.create())
            .client(okHttpClient)
            .build()
}

private val okHttpClient: OkHttpClient by lazy {
    OkHttpClient.Builder()
            .addInterceptor(HttpLoggingInterceptor().apply { level = HttpLoggingInterceptor.Level.HEADERS })
            .build()
}

object GankService {
    private val gankApi: GankApi by lazy { gankRetrofit.create(GankApi::class.java) }

    fun getGankService(): GankApi = gankApi
}

interface GankApi {

    /**
     * 获取分类数据，其中的all可以替换为：
     *  - Android
     *  - 福利
     *  - iOS
     *  - all
     */
    @GET("data/{category}/{size}/{page}")
    fun obtainCategory(
            @Path("size") size: Int,
            @Path("page") page: Int,
            @Path("category") category: String = "all"
    ): Observable<Result>
}
